import React, { useEffect } from 'react';
import { router, withRouter } from 'umi';
import {
    Button,
    Card,
    Row,
    Col,
    Form,
    Spin,
    Divider,
    Popconfirm,
    Empty,
    Input,
    Select,
    Tag,
    Tooltip,
    message
} from 'antd';
import authHelper from '@/utils/auth/helper';
import { useRequest, defaultFormatResult } from '@/hooks';
import IconFont from '@/components/IconFont';
import { FlowIcon } from './components/BasicSettingForm/components';
import { queryTempList, deleteProcess } from './services';
import styles from './formManage.less';

const { checkCode } = authHelper;
const { Option } = Select;

const FormManage = ({ location, form }) => {
    const { getFieldDecorator, setFieldsValue, getFieldsValue } = form;
    const { query = {} } = location;

    // 替换url
    const handleReplacePage = param => {
        history.push({ query: { ...query, ...param } });
    };

    const { data: templateList, loading: listLoading, run: runTemplateList } = useRequest(
        params => queryTempList(params),
        {
            manual: true,
            ...defaultFormatResult
        }
    );

    // 监听条件变化拉取数据
    useEffect(() => {
        runTemplateList(query);
    }, [query, runTemplateList]);

    useEffect(() => {
        setFieldsValue(query);
    }, [query]);

    // 删除流程
    const { run: runDeleteProcess, fetches: deleteProcessFetches } = useRequest(param => deleteProcess(param), {
        manual: true,
        fetchKey: id => id,
        onSuccess: res => {
            const { msg, code } = res;
            if (code === 10000) {
                runTemplateList(query);
                message.success(msg);
            } else {
                message.error(msg);
            }
        }
    });

    const renderList = () =>
        templateList.map(item => (
            <div key={item.category} className={styles.tempListCtr}>
                <div className={styles.tempListTitle}>
                    {item.categoryName} <span>({item.count})</span>
                </div>
                {item && item?.workflowDefProcessDTOList.length > 0 ? (
                    item.workflowDefProcessDTOList.map(subItem => (
                        <div key={subItem.actProcessDeploymentId} className={styles.tempListItem}>
                            <Row>
                                <Col span={8}>
                                    <FlowIcon
                                        value={subItem.iconType}
                                        style={{ position: 'absolute', left: 0, top: 0 }}
                                    />
                                    <div className={styles.iconCell}>
                                        <div className={styles.title} title={subItem.processName}>
                                            {subItem.processName}
                                        </div>
                                        <div className={styles.description} title={subItem.description}>
                                            {subItem.description}
                                        </div>
                                    </div>
                                </Col>
                                <Col span={6}>
                                    <div className={styles.title}>适用公司</div>
                                    <div
                                        className={styles.description}
                                        title={`${subItem.companyName}${
                                            subItem.includeSubCompany === 1 ? '  | 及其附属公司' : ''
                                        }`}
                                    >
                                        {subItem.companyName}
                                        {subItem.includeSubCompany === 1 ? '  | 及其附属公司' : ''}
                                    </div>
                                </Col>
                                <Col span={3}>
                                    <div className={styles.title}>可见范围</div>
                                    <div className={styles.description} title={subItem.scopeFieldLabel}>
                                        {subItem.scopeFieldLabel.join()}
                                    </div>
                                </Col>
                                <Col span={3}>
                                    <span className={styles.action}>
                                        {subItem.status === 1 ? (
                                            <Tag color="#f50">未发布</Tag>
                                        ) : (
                                            <Tag color="#87d068">已发布</Tag>
                                        )}
                                    </span>
                                </Col>
                                <Col span={4}>
                                    <div className={styles.action}>
                                        {checkCode('office:workflow:template:edit') ? (
                                            <Tooltip title="编辑">
                                                <IconFont
                                                    icon="iconlistfunction_edit_icon_default"
                                                    isButton
                                                    onClick={() => {
                                                        history.push(
                                                            `/office/institutions/flowManage/formDesign?id=${subItem.actProcessDeploymentId}&operation=edit`
                                                        );
                                                    }}
                                                />
                                            </Tooltip>
                                        ) : (
                                            ''
                                        )}
                                        {checkCode('office:workflow:template:edit') &&
                                            checkCode('office:workflow:template:switch') && <Divider type="vertical" />}

                                        {checkCode('office:workflow:template:switch') && (
                                            <Popconfirm
                                                title="确认删除？"
                                                onConfirm={() => {
                                                    runDeleteProcess(subItem.id);
                                                }}
                                                okText="确认"
                                                cancelText="取消"
                                            >
                                                <Tooltip title="删除">
                                                    <IconFont
                                                        icon="iconlistfunction_delete_icon_default"
                                                        isButton
                                                        disabled={deleteProcessFetches[subItem.id]?.loading}
                                                    />
                                                </Tooltip>
                                            </Popconfirm>
                                        )}
                                    </div>
                                </Col>
                            </Row>
                        </div>
                    ))
                ) : (
                    <div>
                        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                    </div>
                )}
            </div>
        ));
    return (
        <div>
            <Card style={{ margin: '24px 16px' }}>
                <Row type="flex" justify="space-between">
                    <Col span={18}>
                        <Form layout="inline">
                            <Form.Item label="名称">
                                {getFieldDecorator('processName')(<Input allowClear placeholder="请输入" />)}
                            </Form.Item>
                            <Form.Item label="状态">
                                {getFieldDecorator('status')(
                                    <Select allowClear placeholder="请选择" style={{ width: 120 }}>
                                        <Option value="1">未发布</Option>
                                        <Option value="2">已发布</Option>
                                    </Select>
                                )}
                            </Form.Item>
                            <Form.Item>
                                <Button
                                    type="primary"
                                    onClick={() => {
                                        handleReplacePage(getFieldsValue());
                                    }}
                                >
                                    搜索
                                </Button>
                            </Form.Item>
                        </Form>
                    </Col>
                    <Col span={6} style={{ textAlign: 'right' }}>
                        {checkCode('office:workflow:template:new') ? (
                            <Button
                                type="primary"
                                icon="plus"
                                style={{ marginTop: 3 }}
                                onClick={() => {
                                    history.push('/office/institutions/flowManage/formDesign');
                                }}
                            >
                                创建新审批
                            </Button>
                        ) : (
                            ''
                        )}
                    </Col>
                </Row>
                <Spin spinning={listLoading}>
                    <div className={styles.tempListBox}>
                        {templateList && templateList.length > 0 ? (
                            renderList()
                        ) : (
                            <div>
                                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                            </div>
                        )}
                    </div>
                </Spin>
            </Card>
        </div>
    );
};
export default withRouter(Form.create({ name: 'FormManage' })(FormManage));
